package com.naotebuk.bean;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.naotebuk.entity.Usuario;

public class LoginFilter implements Filter {

	private FilterConfig filterConfig;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	@Override
	public void destroy() {
		this.filterConfig = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpSession session = httpRequest.getSession();
		Usuario usuarioLogado = (Usuario) session.getAttribute("usuarioLogado");
		httpRequest.setCharacterEncoding("UTF-8");
		if (httpRequest.getServletPath().equals("/login.jsf") || httpRequest.getServletPath().contains("/javax.faces.resource")) {
			filterChain.doFilter(request, response);
		} else if (usuarioLogado == null || filterConfig == null) {
			httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsf");
		} else {
			filterChain.doFilter(request, response);
		}
	}

	public FilterConfig getFilterConfig() {
		return filterConfig;
	}

	public void setFilterConfig(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}

}
